import axios from 'axios'
import router from '@/router'

// 请求封装
export const request = axios.create({
  baseURL: 'https://xiaozude.cn:8888/',
  // https://xiaozude.cn:8888/
  // http://172.17.174.174:8888
  headers: {
    'Content-Type': 'application/json'
  }
})

//请求拦截器
request.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem('auth_token')

    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  }, function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.status === 200) {
      if (response.data.data) {
        const { token } = response.data.data
        if (token) {
          localStorage.setItem('auth_token', token)
        }
      }

    }
    return response
  }, function (error) {
    const { status } = error.response
    if (status === 400) {
    } else if (status === 401) {
      localStorage.removeItem("auth_token");
      localStorage.removeItem("User");
      localStorage.removeItem("userInfo");
      router.push("/login");
    } else if (status === 403) {
      router.push("/except/403");
    } else if (status === 404) {
      router.push("/except/404");
    } else if (status >= 500) {
      router.push("/except/500");
    }
    return Promise.reject(error)
  }
)
